/**
 * 应用详情界面
 */
package net.youpo.Market.UI.AppInfo;

import java.io.File;

import net.youpo.Market.R;
import net.youpo.Market.Bean.AppInfoBean;
import net.youpo.Market.Bean.ScreenshotBean;
import net.youpo.Market.Net.HttpConnection;
import net.youpo.Market.UI.StarView;
import net.youpo.Market.Util.ConstantsTable;
import net.youpo.Market.Util.GlobalVariables;
import net.youpo.Market.Util.Tools;
import net.youpo.Market.db.AppInfoTable;
import net.youpo.Market.db.MarketDatabase;
import net.youpo.Market.db.ScreenshotTable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import android.app.ProgressDialog;
import android.app.TabActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

public class AppInfoActivity extends TabActivity {
    private final String REQS_CONFIG = "App/info/";
    private final int REFRESH_ICON = 556;
    private final int LOADING_DONE = 0;
    private TabHost m_tabHost;
    private LayoutInflater mLayoutInflater;
    private AppInfoBean mAppBean = new AppInfoBean();
    private ProgressDialog mLoadingDialog;
    private ImageView mIconIM;
    private TextView mAppNameTV;
    private TextView mAppDownloadCountTV;
    private StarView mAppSV;
    private Class mTopTabClassArray[] = { InfoActivity.class,
            CommentActivity.class };
    private String mTopTabTextArray[] = { "详情", "评论" };
    private View[] mTabViewArr = new View[mTopTabClassArray.length];// 选中的那个View
    private final String APPINFO_LOGTIME = "appinfo_logtime";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAppBean.APP_ID = getIntent().getStringExtra(ConstantsTable.KEY_APPID);
        mAppBean.IS_RECOMMEND = getIntent().getBooleanExtra(
                ConstantsTable.IS_RECOMMEND, false);
        mAppBean.RECOMMEND_ID = getIntent().getStringExtra(
                ConstantsTable.RECOMMEND_ID);
        mLoadingDialog = ProgressDialog.show(this, "", "正在加载. 请等待...", true);
        setContentView(R.layout.appinfo_activity);
        initUI();

        m_tabHost = getTabHost();
        mLayoutInflater = LayoutInflater.from(this);

        new Thread(new Runnable() {
            @Override
            public void run() {
                // 1.判断是否需要更新，如果要更新就清空数据库
                SharedPreferences sPreferences = PreferenceManager
                        .getDefaultSharedPreferences(AppInfoActivity.this);
                long lastUpdateTime = sPreferences.getLong(APPINFO_LOGTIME, 0);
                long nowTime = System.currentTimeMillis();

                if ((nowTime - lastUpdateTime) > GlobalVariables.DATA_REFRESH_TIME) {
                    SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
                    marketDB.execSQL("drop table " + AppInfoTable.TABLE_NAME);
                    marketDB.execSQL("drop table " + ScreenshotTable.TABLE_NAME);
                    MarketDatabase.getMarketDH().onCreate(marketDB,
                            AppInfoTable.sql);
                    MarketDatabase.getMarketDH().onCreate(marketDB,
                            ScreenshotTable.sql);
                }

                // 2.从数据库中查询所需要的数据，如果没有数据就从网络中获取
                int resultCount = getDataFromDB();
                Log.d("H3c", "db");
                if (resultCount == 0) {
                    Log.d("H3c", "net");
                    getDataFromNetwork(sPreferences);
                }
                mHandler.sendEmptyMessage(LOADING_DONE);
            }
        }).start();
    }

    private void initUI() {
        mIconIM = (ImageView) findViewById(R.id.appinfo_icon);
        mAppNameTV = (TextView) findViewById(R.id.appinfo_Name);
        mAppDownloadCountTV = (TextView) findViewById(R.id.appinfo_downloadCount);
        mAppSV = (StarView) findViewById(R.id.appinfo_starView);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case LOADING_DONE: {
                mAppNameTV.setText(mAppBean.APP_NAME);
                try {
                    mAppSV.setPoint(Integer.valueOf(mAppBean.APP_SCORE));
                } catch (Exception e) {
                    mAppSV.setPoint(0);
                }
                mAppDownloadCountTV.setText(mAppBean.DOWNLOAD_COUNT);
                if (mAppBean.APP_ICON_BMP == null) {
                    mIconIM.setImageResource(R.drawable.icon);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            File file = new File(ConstantsTable.CACHE_PATH
                                    + "/" + mAppBean.APP_ID);
                            Bitmap bmp = null;
                            if (file.exists()) {// 如果有缓存文件
                                bmp = Tools
                                        .getBitmapFromCache(ConstantsTable.CACHE_PATH
                                                + "/" + mAppBean.APP_ID);
                            } else {// 没有缓存就从网络获取
                                HttpConnection hc = new HttpConnection();
                                bmp = hc.getNetworkBitmap(mAppBean.APP_ICON);

                                Tools.saveBmpToSd(bmp, mAppBean.APP_ID);// 保存至缓存
                            }
                            Drawable drawable = new BitmapDrawable(bmp);
                            mAppBean.APP_ICON_BMP = drawable;
                            mHandler.sendEmptyMessage(REFRESH_ICON);
                        }
                    }).start();
                } else {
                    mIconIM.setImageDrawable(mAppBean.APP_ICON_BMP);
                }

                int count = mTopTabClassArray.length;
                for (int i = 0; i < count; i++) {
                    TabSpec tabSpec = m_tabHost.newTabSpec(mTopTabTextArray[i])
                            .setIndicator(getTabItemView(i))
                            .setContent(getTabItemIntent(i));
                    m_tabHost.addTab(tabSpec);
                    m_tabHost
                            .setOnTabChangedListener(new OnTabChangeListener() {
                                @Override
                                public void onTabChanged(String tabId) {
                                }
                            });
                }

                dissmissProgressDialog();
                break;
            }
            case REFRESH_ICON:
                if (mAppBean.APP_ICON_BMP != null) {
                    mIconIM.setImageDrawable(mAppBean.APP_ICON_BMP);
                }
                break;
            default:
            }

        }
    };

    private void dissmissProgressDialog() {
        if (mLoadingDialog != null && !isFinishing()
                && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    private int getDataFromDB() {
        int count = 0;// 返回值个数
        // 获得数据库对象
        SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
        // 查询表中的数据
        Cursor cursor = marketDB.query(AppInfoTable.TABLE_NAME, null,
                AppInfoTable.APP_ID + "=?", new String[] { mAppBean.APP_ID },
                null, null, "_id asc");
        // 获取列的索引
        int id = cursor.getColumnIndex(AppInfoTable.ID);
        int appId = cursor.getColumnIndex(AppInfoTable.APP_ID);
        int appName = cursor.getColumnIndex(AppInfoTable.APP_NAME);
        int appIcon = cursor.getColumnIndex(AppInfoTable.APP_ICON);
        int downloadC = cursor.getColumnIndex(AppInfoTable.DOWNLOAD_COUNT);
        int appAuthor = cursor.getColumnIndex(AppInfoTable.APP_AUTHOR);
        int appPack = cursor.getColumnIndex(AppInfoTable.APP_PACK);
        int appVerName = cursor.getColumnIndex(AppInfoTable.APP_VER_NAME);
        int appVer = cursor.getColumnIndex(AppInfoTable.APP_VER);
        int appSize = cursor.getColumnIndex(AppInfoTable.APP_SIZE);
        int appCat = cursor.getColumnIndex(AppInfoTable.APP_CAT);
        int appUrl = cursor.getColumnIndex(AppInfoTable.APP_URL);
        int appLan = cursor.getColumnIndex(AppInfoTable.APP_LANGUAGE);
        int appDesc = cursor.getColumnIndex(AppInfoTable.APP_DESC);
        int appScore = cursor.getColumnIndex(AppInfoTable.APP_SCORE);
        int screenshot = cursor.getColumnIndex(AppInfoTable.SCREENSHOT);
        for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor.moveToNext()) {
            mAppBean.ID = cursor.getString(id);
            mAppBean.APP_ID = cursor.getString(appId);
            mAppBean.APP_NAME = cursor.getString(appName);
            mAppBean.APP_ICON = cursor.getString(appIcon);
            mAppBean.DOWNLOAD_COUNT = cursor.getString(downloadC);
            mAppBean.APP_AUTHOR = cursor.getString(appAuthor);
            mAppBean.APP_PACK = cursor.getString(appPack);
            mAppBean.APP_VER_NAME = cursor.getString(appVerName);
            mAppBean.APP_VER = cursor.getInt(appVer);
            mAppBean.APP_SIZE = cursor.getString(appSize);
            mAppBean.APP_CAT = cursor.getString(appCat);
            mAppBean.APP_URL = cursor.getString(appUrl);
            mAppBean.APP_LANGUAGE = cursor.getString(appLan);
            mAppBean.APP_DESC = cursor.getString(appDesc);
            mAppBean.APP_SCORE = cursor.getString(appScore);
            String[] screenshotArr = cursor.getString(screenshot).split(",");

            ScreenshotBean[] sbArr = new ScreenshotBean[screenshotArr.length];
            for (int i = 0; i < screenshotArr.length; i++) {
                Cursor cursors = marketDB.query(ScreenshotTable.TABLE_NAME,
                        null, ScreenshotTable.ID + "=?",
                        new String[] { screenshotArr[i] }, null, null,
                        "_id asc");
                // 获取列的索引
                int image = cursors.getColumnIndex(ScreenshotTable.IMAGE);
                int thumb = cursors.getColumnIndex(ScreenshotTable.THUMB);
                for (cursors.moveToFirst(); !(cursors.isAfterLast()); cursors
                        .moveToNext()) {
                    sbArr[i] = new ScreenshotBean();
                    sbArr[i].IMAGE = cursors.getString(image);
                    sbArr[i].THUMB = cursors.getString(thumb);
                }
                cursors.close();
            }
            mAppBean.SCREENSHOT = sbArr;
            count++;
        }
        cursor.close();
        return count;
    }

    private void getDataFromNetwork(SharedPreferences sPreferences) {
        HttpConnection hc = new HttpConnection();
        String resultJson = hc.requestService(REQS_CONFIG, new String[] {
                ConstantsTable.KEY_APPID, mAppBean.APP_ID,
                ConstantsTable.KEY_VC, ConstantsTable.NOW_VERSION,
                ConstantsTable.KEY_IMEI, ConstantsTable.IMEI });

        JSONObject person = null;
        try {
            JSONTokener jsonParser = new JSONTokener(resultJson);
            person = (JSONObject) jsonParser.nextValue();
            mAppBean.APP_NAME = person.getString("an");
            mAppBean.APP_ICON = person.getString("icon");
            mAppBean.DOWNLOAD_COUNT = person.getString("dc");
            mAppBean.APP_AUTHOR = person.getString("au");
            mAppBean.APP_PACK = person.getString("pn");
            mAppBean.APP_VER_NAME = person.getString("ver");
            mAppBean.APP_VER = person.getInt("vc");
            mAppBean.APP_SIZE = person.getString("sz");
            mAppBean.APP_CAT = person.getString("cat");
            mAppBean.APP_URL = person.getString("dl");
            mAppBean.APP_LANGUAGE = person.getString("lan");
            mAppBean.APP_DESC = person.getString("desc");
            mAppBean.APP_SCORE = person.getString("score");

            JSONArray jsonArr = person.getJSONArray("st");
            int length = jsonArr.length();
            mAppBean.SCREENSHOT = new ScreenshotBean[length];
            for (int i = 0; i < length; i++) {// 遍历JSONArray
                JSONObject oj = jsonArr.getJSONObject(i);
                ScreenshotBean sb = new ScreenshotBean();
                sb.IMAGE = oj.getString("img");
                sb.THUMB = oj.getString("timg");
                // sb.THUMB =
                // "http://coolapk.com/~/uploads/allimg/120606/2_120606120135_"
                // + (i + 1) + ".jpg";
                sb.DESC = oj.getString("desc");
                mAppBean.SCREENSHOT[i] = sb;
            }
        } catch (JSONException e) {// 如果没有新版本升级就会报这个异常
            Log.e(ConstantsTable.LOG_TAG, "AppInfoActivity json error");
            e.printStackTrace();
        }

        /**
         * 信息存入数据库
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                SQLiteDatabase marketDB = MarketDatabase.getMarketDB();
                // // 1.先清除旧数据
                // // 查询表中的数据
                // Cursor cursor = marketDB
                // .query(AppInfoTable.TABLE_NAME,
                // new String[] { AppInfoTable.SCREENSHOT },
                // AppInfoTable.APP_ID + "=?",
                // new String[] { mAppBean.APP_ID }, null, null,
                // "_id asc");
                // // 获取列的索引
                // int scre = cursor.getColumnIndex(AppInfoTable.SCREENSHOT);
                // String screenshotArrStr = null;// 数据库中保存的截图表id
                // for (cursor.moveToFirst(); !(cursor.isAfterLast()); cursor
                // .moveToNext()) {
                // screenshotArrStr = cursor.getString(scre);
                // }
                // if (screenshotArrStr != null) {
                // String[] scrArr = screenshotArrStr.split(",");
                // for (int i = 0; i < scrArr.length; i++) {
                // marketDB.delete(ScreenshotTable.TABLE_NAME,
                // ScreenshotTable.ID + "=?",
                // new String[] { scrArr[i] });
                // }
                // }
                // marketDB.delete(AppInfoTable.TABLE_NAME, AppInfoTable.APP_ID
                // + "=?", new String[] { mAppBean.APP_ID });

                // 2.插入新数据
                ContentValues cv = new ContentValues();
                StringBuffer sBuffer = new StringBuffer();
                if (mAppBean.SCREENSHOT != null) {
                    for (int n = 0; n < mAppBean.SCREENSHOT.length; n++) {
                        ScreenshotBean sb = mAppBean.SCREENSHOT[n];
                        cv.put(ScreenshotTable.IMAGE, sb.IMAGE);
                        cv.put(ScreenshotTable.THUMB, sb.THUMB);
                        cv.put(ScreenshotTable.DESC, sb.DESC);
                        long id = marketDB.insert(ScreenshotTable.TABLE_NAME,
                                null, cv);
                        sBuffer.append(id + ",");
                    }
                }

                ContentValues tcv = new ContentValues();
                tcv.put(AppInfoTable.APP_ID, mAppBean.APP_ID);
                tcv.put(AppInfoTable.APP_NAME, mAppBean.APP_NAME);
                tcv.put(AppInfoTable.APP_ICON, mAppBean.APP_ICON);
                tcv.put(AppInfoTable.DOWNLOAD_COUNT, mAppBean.DOWNLOAD_COUNT);
                tcv.put(AppInfoTable.APP_AUTHOR, mAppBean.APP_AUTHOR);
                tcv.put(AppInfoTable.APP_PACK, mAppBean.APP_PACK);
                tcv.put(AppInfoTable.APP_VER_NAME, mAppBean.APP_VER_NAME);
                tcv.put(AppInfoTable.APP_VER, mAppBean.APP_VER);
                tcv.put(AppInfoTable.APP_SIZE, mAppBean.APP_SIZE);
                tcv.put(AppInfoTable.APP_CAT, mAppBean.APP_CAT);
                tcv.put(AppInfoTable.APP_URL, mAppBean.APP_URL);
                tcv.put(AppInfoTable.APP_LANGUAGE, mAppBean.APP_LANGUAGE);
                tcv.put(AppInfoTable.APP_DESC, mAppBean.APP_DESC);
                tcv.put(AppInfoTable.APP_SCORE, mAppBean.APP_SCORE);
                tcv.put(AppInfoTable.SCREENSHOT, sBuffer.toString());

                marketDB.insert(AppInfoTable.TABLE_NAME, null, tcv);
            }
        }).start();

        // 保存刷新值
        SharedPreferences.Editor editor_isstop = sPreferences.edit();
        editor_isstop.putLong(APPINFO_LOGTIME, System.currentTimeMillis());
        editor_isstop.commit();
    }

    private View getTabItemView(int index) {
        View view = mLayoutInflater.inflate(R.layout.tab_item_view, null);
        TextView textView = (TextView) view.findViewById(R.id.textview);
        textView.setText(mTopTabTextArray[index]);
        switch (index) {
        case 0:
            view.setBackgroundResource(R.drawable.manager_tab_download_selector);
            break;
        case 1:
            view.setBackgroundResource(R.drawable.manager_tab_favorites_selector);
            break;
        }
        mTabViewArr[index] = view;
        return view;
    }

    private Intent getTabItemIntent(int index) {
        Intent intent = new Intent(this, mTopTabClassArray[index]);
        Bundle mBundle = new Bundle();
        mBundle.putSerializable(ConstantsTable.KEY_VC, mAppBean);
        intent.putExtras(mBundle);
        return intent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        dissmissProgressDialog();
    }

}
